﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fis.Win.Utils;

namespace Fis.Win.Forms
{
    public partial class DetailReportForm : ReportBaseForm
    {
        public DetailReportForm()
        {
            InitializeComponent();
            InitializeViewUI();
            InitializeBinding();
        }

        protected DataRow AccountInfo { get; set; }

        protected override void ShowFilter()
        {
            var f = new ReportFilterForm();

            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ///获取周期过滤条件
                RangeFilter = f.RangeFilter;
                ///获取科目过滤条件
                AccFilter = (f.AccountFilter == null) ? "default_1001" : f.AccountFilter.ToString();

                AccountInfo = Fis.Win.Utils.CacheContext.GetCache("TACCOUNT").Select("SID='" + AccFilter + "'")[0];

                InitializeBinding();
            }
        }

        public override void InitializeBinding()
        {
            //report_detail
            //0 RANGEFILTER
            //1 ACCCODE
            //2 FIRSTRANGE
            //3 ACCSID
            // 4 STARTDATE
            var xml = Agile.Engine.ObjectContext.GetResource("SqlResource");
            var sql = xml.Format("report_detail", RangeFilter, AccountInfo["FCODE"], RangeFilter.Substring(0, 1),
                AccFilter, string.Format("{0}-{1}-1 00:00:00", AppSession.Year, RangeFilter.Substring(0, 1)));
            Fis.Win.Utils.UIUtils.LookUpBinding(repFX, Fis.Win.Utils.CacheContext.DebitCreditCache(), "display", "value");
            var data = Agile.Engine.Data.DataContext.Get("CacheDataContext").DefaultModel.QueryTable(CommandType.Text, "RestReport", sql);
            var detail = ProcessDetailData(data);
            detail.DefaultView.Sort = "FENTERDATE,FBILLNO";
            gridControl1.DataSource = detail;
            gridControl1.DefaultView.ViewCaption = AccountInfo["FDETAILNAME"].ToString();
        }

        DataTable ProcessDetailData(DataTable data)
        {
            data.Columns.Add("FX", typeof(int));
            data.Columns.Add("YE", typeof(decimal));

            decimal last = 0m;
            var isDebit = (AccountInfo["FJD"].Equals("1"));
            foreach (var d in data.AsEnumerable())
            {
                var jf = NullParse(d["J"]);
                var df = NullParse(d["D"]);
                if (isDebit && !Agile.Engine.Utils.StringUtils.IsEmpty(d["FBILLNO"])) // 借方科目
                {
                    last = last + jf - df;
                }
                d["YE"] = last;

                if (last == 0)
                    d["FX"] = 0;
                else if (isDebit && last > 0)
                    d["FX"] = 1;
                else
                    d["FX"] = 2;

            }

            return data;
        }

        decimal NullParse(object value)
        {
            if (value == null || value == DBNull.Value || string.IsNullOrEmpty(value.ToString()))
                return 0m;
            return decimal.Parse(value.ToString());
        }

        public override void InitializeViewUI()
        {
            InitializeNavButton();
            theGridControl = gridControl1;

            ///获取周期过滤条件
            RangeFilter = (int.Parse(Fis.Win.Utils.AppSession.Range) - 1).ToString();
            ResetAccountInfo("default_1001");
        }

        void InitializeNavButton()
        {
            var iPrev = new DevExpress.XtraBars.BarButtonItem();
            var iNext = new DevExpress.XtraBars.BarButtonItem();

            barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
            iPrev,
            iNext});

            bar2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
            new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.PaintStyle, iPrev, DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph),
            new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.PaintStyle, iNext, DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph),
            });

            // 
            // iPrev
            // 
            iPrev.Caption = "上一个";
            iPrev.Id = 4;
            iPrev.ImageIndex = 14;
            iPrev.Name = "iPrev";
            iPrev.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(
                (sender, e) => { GotoAccount(-1); });

            // 
            // iNext
            // 
            iNext.Caption = "下一个";
            iNext.Id = 5;
            iNext.ImageIndex = 13;
            iNext.Name = "iNext";
            iNext.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(
                (sender, e) => { GotoAccount(1); });

        }

        void GotoAccount(int nav)
        {
            var filter = "FPARENT IS NULL AND ";
            if (nav < 0) //上一个
            {
                filter += string.Format("FCODE < '{0}'", AccountInfo["FCODE"]);
            }
            else
            {
                filter += string.Format("FCODE > '{0}'", AccountInfo["FCODE"]);
            }

            var data = Fis.Win.Utils.CacheContext.GetCache("TACCOUNT").Select(filter);
            if (data.Length == 0)
            {
                return;
            }

            var code = data[(nav < 0) ? data.Length - 1 : 0]["SID"].ToString();
            ResetAccountInfo(code);
            InitializeBinding();

        }

        public void ResetAccountInfo(string accCode)
        {
            ///获取科目过滤条件
            AccFilter = accCode;// "default_1001";

            AccountInfo = Fis.Win.Utils.CacheContext.GetCache("TACCOUNT").Select("SID='" + AccFilter + "'")[0];
        }

        protected override void InitializeResetColumns(DataTable data)
        {
        }

        private void gridControl1_DoubleClick(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0)
                return;

            var data = gridView1.GetFocusedDataRow();
            var billNo = Agile.Engine.Utils.DataUtils.Parse<decimal>(-1m, data["FBILLNO"]);
            if (billNo < 0)
            {
                MessageBox.Show("请选择包含凭证号的有效行进行查看");
                return;
            }

            ShowDetial(data[0].ToString());
        }

        protected override void ShowView()
        {
            gridControl1_DoubleClick(null, null);
        }

        protected override void ShowDetial(object state)
        {
            var model = new System.Collections.Hashtable();
            model["SID"] = state;
            UIManager.ShowEdit<Forms.BillEditForm>("BillEditViewProvider", Agile.Engine.View.ViewState.Modify, model);
        }
    }
}
